<template>
  <div class="order-hall-container">
    <!-- 筛选表单等其他内容 -->
    <el-card class="order-list">
      <template #header>
        <div class="header">
          <div class="title">可接订单</div>
          <!-- 排序等内容 -->
        </div>
      </template>
      <div class="order-items">
        <el-card
          v-for="order in orderList"
          :key="order.id"
          class="order-item"
          shadow="hover"
        >
          <!-- 订单头部信息 -->
          <div class="order-header">
            <div class="left">
              <!-- 只显示有值的服务类型 -->
              <el-tag v-if="order.serviceType" type="success">{{ order.serviceType }}</el-tag>
              <!-- 只显示有值的发布时间 -->
              <span v-if="order.publishTime" class="time">{{ order.publishTime }}</span>
            </div>
            <div class="right">
              <!-- 只显示有值的距离 -->
              <span v-if="order.distance" class="distance">{{ order.distance }}km</span>
            </div>
          </div>
          <!-- 订单内容信息 -->
          <div class="order-content">
            <div class="main-info">
              <div class="service-info">
                <h4>服务信息</h4>
                <p>服务开始时间：{{ formatStartTime(order.starttime) }}</p>
                <p>服务时长：{{ formatDuration(order.time) }}</p>
                <p>服务地点：{{ order.hospital || '未知服务地点' }}</p>
                <p>服务科室：{{ order.department || '未知服务科室' }}</p>
              </div>
              <div class="patient-info">
                <h4>患者信息</h4>
                <p>姓名：{{ order.name || '未知姓名' }}</p>
                <p>性别：{{ order.gender || '未知性别' }}</p>
                <p>年龄：{{ order.age || '未知年龄' }}岁</p>
                <p>联系电话：{{ order.phone || '未知电话' }}</p>
              </div>
            </div>
            <div class="price-info">
              <div class="amount">￥200</div>
              <el-button
                type="primary"
                :disabled="order.caregiverid !== null"
                 @click="handleAcceptOrder(order)"
              >
                {{ getActionText(order) }}
              </el-button>
            </div>
          </div>
          <!-- 订单底部信息 -->
          <div class="order-footer">
            <div class="requirements">
              <h4>服务要求</h4>
              <!-- 假设 requirements 字段需要根据实际情况处理 -->
              <p v-html="order.requirements || '无特殊要求'"></p>
            </div>
          </div>
        </el-card>
        <!-- 无订单时的提示 -->
        <el-empty v-if="!orderList.length" description="暂无可接订单" />
      </div>
      <!-- 分页组件 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 抢单确认对话框 -->
    <el-dialog
      v-model="confirmDialogVisible"
      title="抢单确认"
      width="400px"
    >
      <div class="confirm-content">
        <p>订单信息：</p>
        <!-- 只显示有值的服务类型 -->
        <p v-if="selectedOrder?.serviceType">服务类型：{{ selectedOrder?.serviceType }}</p>
        <p>服务开始时间：{{ formatStartTime(selectedOrder?.starttime) || '未知服务开始时间' }}</p>
        <p>服务时长：{{ formatDuration(selectedOrder?.time) || '未知服务时长' }}</p>
        <!-- 只显示有值的服务地点 -->
        <p v-if="selectedOrder?.hospital">服务地点：{{ selectedOrder?.hospital }}</p>
        <!-- 只显示有值的服务科室 -->
        <p v-if="selectedOrder?.department">服务科室：{{ selectedOrder?.department }}</p>
        <p>服务金额：￥200</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="confirmDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAcceptOrder">确认抢单</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import {ip} from '@/router/ip.js'

// 订单列表数据
const orderList = ref([])
// 当前页码
const currentPage = ref(1)
// 每页显示数量
const pageSize = ref(10)
// 总记录数
const total = ref(0)
// 筛选表单数据
const filterForm = reactive({
  serviceType: '',
  area: []
})
// 排序类型
const sortType = ref('time')
// 抢单确认对话框显示状态
const confirmDialogVisible = ref(false)
// 选中的订单
const selectedOrder = ref(null)

// 获取公共订单
const fetchPublicOrders = async () => {
    const response = await axios.get(`http://${ip}:8000/api/getPublicOrders`, {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    });
    console.log('获取订单成功:', response.data); // 添加日志
    orderList.value = response.data.data;
    total.value = response.data.total;
};

// 抢单处理
const confirmAcceptOrder = async () => {
  console.log('确认抢单，选中的订单:', selectedOrder.value); // 添加日志
    const caregiverid = localStorage.getItem('caregiverId');
    console.log('当前陪护师ID:', caregiverid); // 添加日志
    if (!caregiverid) throw new Error('请先登录');

    console.log('发送抢单请求:', { orderid: selectedOrder.value.id, caregiverid }); // 添加日志
    await axios.post(`http://${ip}:8000/api/acceptOrder`, {
      orderid: selectedOrder.value.id,
      caregiverid: caregiverid
    });

    ElMessage.success('抢单成功');
    confirmDialogVisible.value = false;
    await fetchPublicOrders(); // 重新获取订单列表
};

// 查询按钮点击事件
const handleSearch = () => {
  // 实现查询逻辑
}

// 处理抢单按钮点击
const handleAcceptOrder = (order) => {
  console.log('点击抢单按钮，选中的订单:', order); // 添加日志
  selectedOrder.value = order;
  confirmDialogVisible.value = true;
};

const getActionText = (order) => {
  return order.caregiverid ? '已抢单' : '抢单';
};

// 处理每页数量变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  fetchPublicOrders()
}

// 处理当前页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  fetchPublicOrders()
}

// 格式化服务开始时间
const formatStartTime = (starttime) => {
  if (starttime) {
    const date = new Date(starttime);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  }
  return '未知服务开始时间';
}

// 格式化服务时长
const formatDuration = (time) => {
  if (typeof time === 'number') {
    const hours = Math.floor(time / 3600);
    return `${hours}小时`;
  }
  return '未知服务时长';
}

onMounted(() => {
  fetchPublicOrders()
})
</script>

<style scoped>
/* 样式部分 */
.order-hall-container {
  padding: 20px;
}
.order-list {
  margin-top: 20px;
}
.order-item {
  margin-bottom: 20px;
}
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.order-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.main-info {
  display: flex;
  gap: 20px;
}
.price-info {
  text-align: right;
}
.amount {
  font-size: 24px;
  color: #f56c6c;
  font-weight: bold;
  }
</style>